from rest_framework import serializers
from alipay import AliPay
from django.conf import settings
from shopping.settings import APP_PRIVATE_KEY, ALIPAY_PUBLIC_KEY
import time

from goods.models import Goods
from .models import ShoppingCart,OrderInfo,OrderGoods


class GoodsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Goods
        fields = "__all__"
class ListShoppingCartSerializer(serializers.ModelSerializer):
    goods = GoodsSerializer(many=False)
    class Meta:
        model = ShoppingCart
        fields = "__all__"



class ShoppingCartSerializer(serializers.Serializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    goods = serializers.PrimaryKeyRelatedField(queryset=Goods.objects.all(), )
    nums = serializers.IntegerField(required=True, min_value=1,
                                    error_messages={"required": "请选择购买数量",
                                                    "min_value": "购买数量不能小于1"})

    def create(self, validated_data):
        user = self.context["request"].user
        goods = validated_data["goods"]
        nums = validated_data["nums"]

        # 查询记录是否存在
        is_sc = ShoppingCart.objects.filter(user=user, goods=goods)
        if is_sc:
            is_sc = is_sc[0]
            # 存在购买数量+1
            is_sc.nums += nums
            is_sc.save()
        else:
            #不存在记录则新建购买
            is_sc = ShoppingCart.objects.create(**validated_data)

            # 返回记录后面还要做序列化
        return is_sc
    # def update(self, instance, validated_data):
    #     instance.nums = validated_data["nums"]
    #     instance.save()
    #     return instance
    def update(self, instance, validated_data):
        # 修改商品数量
        instance.nums = validated_data["nums"]
        instance.save()
        return instance

class OrderSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )

    pay_status = serializers.CharField(read_only=True)
    trade_no = serializers.CharField(read_only=True)
    order_sn = serializers.CharField(read_only=True)
    pay_time = serializers.DateTimeField(read_only=True)
    nonce_str = serializers.CharField(read_only=True)
    add_time = serializers.DateTimeField(read_only=True)


    alipay_url = serializers.SerializerMethodField(read_only=True)

    #给alipay_url赋值
    def get_alipay_url(self,obj):   #obj是当前Serializer对象
        # 读取私钥
        app_private_key_string = open(APP_PRIVATE_KEY).read()
        # 读取公钥
        alipay_public_key_string = open(ALIPAY_PUBLIC_KEY).read()

        # 加密解密
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,  # APPID
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,  # 私钥
            alipay_public_key_string=alipay_public_key_string,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=True,  # 是否调试模式
        )
        subject = "测试订单"
        order_string = alipay.api_alipay_trade_page_pay(
            qr_pay_mode=False,  # 是否扫码支付
            out_trade_no=obj.order_sn,  # 订单号
            total_amount=obj.order_mount,  # 支付金额
            subject=subject,  # 支付商品名称
            # 如需要传更多的字段自己查api

            return_url="",  # 在支付页面支付完成跳转到此页面，可以跳转到商城主页
            notify_url="http://107.191.53.243:80/alipay/return"  # 异步，任意情况下支付时跳转到此页面，以POST形式返回参数
        )

        # 支付连接
        re_url = settings.ALIPAY_URL + order_string
        print(re_url)
        return re_url


    def generate_order_sn(self):
        # 当前时间+userid+随机数
        from random import Random
        random_ins = Random()
        order_sn = "{time_str}{userid}{ranstr}".format(time_str=time.strftime("%Y%m%d%H%M%S"),
                                                       userid=self.context["request"].user.id,
                                                       ranstr=random_ins.randint(10, 99))

        return order_sn

    def validate(self, attrs):
        attrs["order_sn"] = self.generate_order_sn()
        return attrs

    class Meta:
        model = OrderInfo
        fields = "__all__"

class OrderGoodsSerialzier(serializers.ModelSerializer):
    goods = GoodsSerializer(many=False)

    class Meta:
        model = OrderGoods
        fields = "__all__"

class OrderDetailSerializer(serializers.ModelSerializer):
    # 一个订单有多个订单商品项
    goods = OrderGoodsSerialzier(many=True)

    alipay_url = serializers.CharField(read_only=True)

    # 给alipay_url赋值
    def get_alipay_url(self, obj):  # obj是当前Serializer对象
        # 读取私钥
        app_private_key_string = open(APP_PRIVATE_KEY).read()
        # 读取公钥
        alipay_public_key_string = open(ALIPAY_PUBLIC_KEY).read()

        # 加密解密
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,  # APPID
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,  # 私钥
            alipay_public_key_string=alipay_public_key_string,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=True,  # 是否调试模式
        )
        subject = "测试订单"
        order_string = alipay.api_alipay_trade_page_pay(
            qr_pay_mode=False,  # 是否扫码支付
            out_trade_no=obj.order_sn,  # 订单号
            total_amount=obj.order_mount,  # 支付金额
            subject=subject,  # 支付商品名称
            # 如需要传更多的字段自己查api

            return_url="",  # 在支付页面支付完成跳转到此页面，可以跳转到商城主页
            notify_url="http://107.191.53.243:80/alipay/return"  # 异步，任意情况下支付时跳转到此页面，以POST形式返回参数
        )

        # 支付连接
        re_url = settings.ALIPAY_URL + order_string
        return re_url

    class Meta:
        model = OrderInfo
        fields = "__all__"